import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { SmartClassificationService, defaultSmartClassificationConfig } from '@/services/smartClassification'
import type { TaskClassification } from '@/types/smartList'

export interface Task {
  id: string
  title: string
  description?: string
  completed: boolean
  category: 'today' | 'important' | 'planned' | 'assigned' | 'tasks'
  createdAt: Date
  updatedAt?: Date
  dueDate?: Date
  deadline?: string
  reminder?: string
  repeat?: {
    type: string
    customDays?: number
  }
  priority?: 'low' | 'medium' | 'high'
  tags?: string[]
  listIds?: string[] // 任务所属的清单ID列表
  isImportant?: boolean
  estimatedTime?: number // 预估完成时间（分钟）
  actualTime?: number // 实际完成时间（分钟）
}

export const useTaskStore = defineStore('tasks', () => {
  // 任务列表
  const tasks = ref<Task[]>([
    {
      id: '1',
      title: '完成项目文档',
      completed: false,
      category: 'today',
      createdAt: new Date(),
      deadline: '2025-01-25T18:00:00.000Z',
      reminder: '2025-01-25T16:00:00.000Z',
      repeat: {
        type: 'weekly'
      }
    },
    {
      id: '2',
      title: '重要会议准备',
      completed: false,
      category: 'important',
      createdAt: new Date(),
      deadline: '2025-01-24T09:00:00.000Z',
      reminder: '2025-01-24T08:30:00.000Z'
    },
    {
      id: '3',
      title: '计划中的任务',
      completed: false,
      category: 'planned',
      createdAt: new Date(),
      repeat: {
        type: 'daily'
      }
    },
    {
      id: '4',
      title: '分配给我的任务',
      completed: false,
      category: 'assigned',
      createdAt: new Date(),
      deadline: '2025-01-26T17:00:00.000Z'
    },
    {
      id: '5',
      title: '一般任务',
      completed: false,
      category: 'tasks',
      createdAt: new Date(),
      repeat: {
        type: 'custom',
        customDays: 3
      }
    }
  ])

  // 智能分类服务
  const classificationService = new SmartClassificationService(defaultSmartClassificationConfig)
  
  // 任务分类结果
  const taskClassifications = ref<Map<string, TaskClassification>>(new Map())

  // 智能分类计算属性
  const todayTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('today') && !task.completed
    })
  )
  
  const tomorrowTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('tomorrow') && !task.completed
    })
  )
  
  const weekTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('week') && !task.completed
    })
  )
  
  const importantTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('important') && !task.completed
    })
  )
  
  const plannedTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('planned') && !task.completed
    })
  )
  
  const completedTasks = computed(() => 
    tasks.value.filter(task => task.completed)
  )
  
  const overdueTasks = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('overdue') && !task.completed
    })
  )
  
  // 计算各分类的任务数量
  const todayCount = computed(() => todayTasks.value.length)
  const tomorrowCount = computed(() => tomorrowTasks.value.length)
  const weekCount = computed(() => weekTasks.value.length)
  const importantCount = computed(() => importantTasks.value.length)
  const plannedCount = computed(() => plannedTasks.value.length)
  const completedCount = computed(() => completedTasks.value.length)
  const overdueCount = computed(() => overdueTasks.value.length)
  const assignedCount = computed(() => 
    tasks.value.filter(task => task.category === 'assigned' && !task.completed).length
  )
  const tasksCount = computed(() => 
    tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes('tasks') && !task.completed
    }).length
  )

  // 重新分类所有任务
  const reclassifyAllTasks = () => {
    tasks.value.forEach(task => {
      const classification = classificationService.classifyTask(task)
      taskClassifications.value.set(task.id, classification)
    })
  }

  // 重新分类单个任务
  const reclassifyTask = (taskId: string) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (task) {
      const classification = classificationService.classifyTask(task)
      taskClassifications.value.set(task.id, classification)
    }
  }

  // 根据清单ID获取任务
  const getTasksByListId = (listId: string) => {
    return tasks.value.filter(task => {
      const classification = taskClassifications.value.get(task.id)
      return classification?.categories.includes(listId)
    })
  }

  // 别名方法，保持兼容性
  const getTasksByList = getTasksByListId

  // 添加任务
  const addTask = (task: Omit<Task, 'id' | 'createdAt'>) => {
    const newTask: Task = {
      ...task,
      id: Date.now().toString(),
      createdAt: new Date(),
      updatedAt: new Date()
    }
    tasks.value.push(newTask)
    // 立即对新任务进行分类
    reclassifyTask(newTask.id)
  }

  // 切换任务完成状态
  const toggleTask = (taskId: string) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (task) {
      task.completed = !task.completed
      task.updatedAt = new Date()
      // 重新分类任务
      reclassifyTask(taskId)
    }
  }

  // 删除任务
  const deleteTask = (taskId: string) => {
    const index = tasks.value.findIndex(t => t.id === taskId)
    if (index > -1) {
      tasks.value.splice(index, 1)
      // 删除分类信息
      taskClassifications.value.delete(taskId)
    }
  }

  // 更新任务
  const updateTask = (id: string, updatedTask: Partial<Task>) => {
    const index = tasks.value.findIndex(task => task.id === id)
    if (index > -1) {
      tasks.value[index] = { 
        ...tasks.value[index], 
        ...updatedTask,
        updatedAt: new Date()
      }
      // 重新分类任务
      reclassifyTask(id)
    }
  }

  // 根据分类获取任务
  const getTasksByCategory = (category: Task['category']) => {
    return tasks.value.filter(task => task.category === category)
  }

  // 初始化时对所有任务进行分类
  reclassifyAllTasks()

  // 监听任务变化，自动重新分类
  watch(
    () => tasks.value.length,
    () => {
      // 当任务数量变化时，重新分类所有任务
      reclassifyAllTasks()
    },
    { immediate: false }
  )

  return {
    tasks,
    taskClassifications,
    // 任务列表
    todayTasks,
    tomorrowTasks,
    weekTasks,
    importantTasks,
    plannedTasks,
    completedTasks,
    overdueTasks,
    // 任务计数
    todayCount,
    tomorrowCount,
    weekCount,
    importantCount,
    plannedCount,
    completedCount,
    overdueCount,
    assignedCount,
    tasksCount,
    // 任务操作
    addTask,
    toggleTask,
    deleteTask,
    updateTask,
    getTasksByCategory,
    getTasksByListId,
    getTasksByList,
    // 分类操作
    reclassifyAllTasks,
    reclassifyTask,
    classificationService
  }
})